package com.study.concurrent.A_ThreadManagement.j_ThreadGroup;

import java.util.concurrent.TimeUnit;

/**
 * Created by 赵超 on 2017/3/19.
 */
public class Main {
    public static void main(String[] args) {
        ThreadGroup threadGroup = new ThreadGroup("Searcher");
        Result result = new Result();
        SearchTask searchTask = new SearchTask(result);
        for (int i = 0; i < 5; i++) {
            Thread thread = new Thread(threadGroup, searchTask);
            thread.start();
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.printf("线程数量 : %d\n", threadGroup.activeCount());
        /**
         * 打印线程组信息
         */
        System.out.printf("线程组信息 : \n");
        threadGroup.list();
        /**
         * 将线程对象放入数组
         */
        Thread[] threads = new Thread[threadGroup.activeCount()];
        threadGroup.enumerate(threads);
        /**
         * 输出每个线程对象的名称和状态
         * activeCount()方法：
         *      返回此线程组及其子组中活动线程数的估计值，递归遍历该线程组中的所有子群。
         */
        for (int i = 0; i < threadGroup.activeCount(); i++) {
            System.out.printf("线程 %s: %s\n", threads[i].getName(), threads[i].getState());
        }
        waitFinish(threadGroup);
        threadGroup.interrupt();
    }

    /**
     * 检测是否有线程运行结束
     *
     * @param threadGroup
     */
    private static void waitFinish(ThreadGroup threadGroup) {
        while (threadGroup.activeCount() > 4) {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
